package com.bdy.lm.taximanager.service;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;

import com.bdy.lm.taximanager.app.MyApp;
import com.bdy.lm.taximanager.thread.HeartBitThread;
import com.bdy.lm.taximanager.thread.LocationReportThread;
import com.bdy.lm.taximanager.thread.QueryCommandThread;
import com.bdy.lm.taximanager.thread.WeatherThread;

import java.util.Iterator;

public class MyService extends Service {

    private LocationManager locationManager;
    private LocationReportThread locationReportThread = new LocationReportThread();
    private HeartBitThread heartBitThread = new HeartBitThread();
    //private SerialDataThread serialDataThread = new SerialDataThread();
    private QueryCommandThread queryCommandThread = new QueryCommandThread();
    private WeatherThread weatherThread = new WeatherThread();
    private String TAG = "GPS";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        final Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, new LocationListener() {
            @Override//每隔0.5秒获取一次GPS定位信息，改变的最小距离1米
            public void onLocationChanged(Location location) {
                //当坐标改变时候触发该函数，如果Provider传相同的坐标，它就不会触发。
                update(location);
            }

            @Override
            public void onStatusChanged(String s, int status, Bundle bundle) {
                //Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
                switch (status) {
                    //GPS状态为可见时
                    case LocationProvider.AVAILABLE:
                        //Log.i(TAG, "当前GPS状态为可见状态");
                        break;
                    //GPS状态为服务区外时
                    case LocationProvider.OUT_OF_SERVICE:
                        //Log.i(TAG, "当前GPS状态为服务区外状态");
                        break;
                    //GPS状态为暂停服务时
                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        //Log.i(TAG, "当前GPS状态为暂停服务状态");
                        break;
                }
            }

            @Override
            public void onProviderEnabled(String s) {
                //GPS LocationProvider启用时触发此函数，比如GPS被打开
                update(location);
            }

            @Override
            public void onProviderDisabled(String s) {
                //GPS LocationProvider禁用时触发此函数，比如GPS被关闭
            }
        });
        //位置汇报线程
        locationReportThread.start();
        //System.out.println("位置线程ID"+locationReportThread.getId());
        //心跳线程
        heartBitThread.start();
        //周期接收串口数据
        //serialDataThread.start();
        //定时访问服务器，查询指令
        queryCommandThread.start();
        //查询天气线程
        weatherThread.start();

        //状态监听
        GpsStatus.Listener listener = new GpsStatus.Listener() {
            public void onGpsStatusChanged(int event) {
                switch (event) {
                    //第一次定位
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        //Log.i(TAG, "第一次定位");
                        break;
                    //卫星状态改变
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                        //Log.i(TAG, "卫星状态改变");
                        //获取当前状态
                        try{
                            GpsStatus gpsStatus  =locationManager.getGpsStatus(null);

                            //获取卫星颗数的默认最大值
                            int maxSatellites = gpsStatus.getMaxSatellites();
                            //创建一个迭代器保存所有卫星
                            Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                            int count = 0;
                            while (iters.hasNext() && count <= maxSatellites) {
                                GpsSatellite s = iters.next();
                                count++;
                            }
                            //System.out.println("搜索到："+count+"颗卫星");
                        }catch (SecurityException e){
                            e.printStackTrace();
                        }
                        break;
                    //定位启动
                    case GpsStatus.GPS_EVENT_STARTED:
                        //Log.i(TAG, "定位启动");
                        break;
                    //定位结束
                    case GpsStatus.GPS_EVENT_STOPPED:
                        //Log.i(TAG, "定位结束");
                        break;
                }
            };
        };
        //绑定监听状态
        locationManager.addGpsStatusListener(listener);
    }



    //位置信息改变时修改全局静态变量
    public void update(Location newLocation) {
        if (newLocation != null) {
            MyApp.locationMessageBody.setLongitude(newLocation.getLongitude());
            MyApp.locationMessageBody.setLatitude(newLocation.getLatitude());
            MyApp.locationMessageBody.setDirection(newLocation.getBearing() / 2);
            MyApp.locationMessageBody.setSpeed(newLocation.getSpeed());
            MyApp.locationMessageBody.setAltitude(newLocation.getAltitude());
            System.out.println("位置修改，GPS时间是："+newLocation.getTime());
        }
    }

}
